﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Newtor.VoteMan.Providers
{
    public class LinqVoteProjectManager : IVoteProjectManager
    {
        #region IVoteProjectManager 成员

        public void CreateVoteProject(VoteProject vp)
        {
            using (VoteDataContext cdc = new VoteDataContext())
            {
                cdc.VoteProject.InsertOnSubmit(vp);
                cdc.SubmitChanges();
            }
        }

        public VoteProject GetVoteProject(Guid vpId)
        {
            using (VoteDataContext vdc = new VoteDataContext())
            {
                try
                {
                    return vdc.VoteProject.Single(project => project.ProjectId == vpId);
                }
                catch (InvalidOperationException)
                {
                    return null;
                }
            }
        }

        public VoteProject[] All
        {
            get
            {
                using (VoteDataContext vdc = new VoteDataContext())
                {
                    return vdc.VoteProject.ToArray();
                }
            }
        }


        public void UpdateVoteProject(VoteProject vp)
        {
            using (VoteDataContext vdc = new VoteDataContext())
            {
                VoteProject oldVp = vdc.VoteProject.Single(p => p.ProjectId == vp.ProjectId);
                oldVp.Creator = vp.Creator;
                oldVp.Name = vp.Name;
                oldVp.ParentProjectId = vp.ParentProjectId;
                oldVp.Order = vp.Order;

                vdc.SubmitChanges();
            }
        }


        public VoteProject[] RootProjects
        {
            get
            {
                using (VoteDataContext vdc = new VoteDataContext())
                {
                    return vdc.VoteProject.Where(vp => vp.ParentProject == null).ToArray();
                }
            }
        }


        public VoteProject GetRootProjectByItemId(Guid viId)
        {
            using (VoteDataContext vdc = new VoteDataContext())
            {
                var vi = vdc.VoteItem.Single(i => i.ItemId == viId);
                var vp = vi.Project;
                if (vp.ParentProject != null)
                {
                    return GetRootProjectByItemId(vp.ParentProjectId.Value);
                }
                return vp;
            }
        }


        public VoteProject GetRootProject(Guid vpId)
        {
            using (VoteDataContext vdc = new VoteDataContext())
            {
                var vp = GetVoteProject(vpId);
                if (vp.ParentProjectId.HasValue)
                {
                    return GetRootProject(vp.ParentProjectId.Value);
                }
                return vp;
            }
        }

        #endregion
    }
}
